package com.rainner.app.action;

import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.rainner.app.base.action.JsonAction;
import com.rainner.app.server.BookServer;

@Results({ @Result(name = "LIST", type = "freemarker", location = "/WEB-INF/content/public/list.ftl"), @Result(name = "OUTLOGIN", type = "redirect", location = "/login.html"), @Result(name = "ERROR", type = "redirect", location = "/error.html") })
public class ListAction extends JsonAction {
	private static final long serialVersionUID = 1L;
	private String type;
	private String name;
	private String value;
	private final String base = "/list";
	private BookServer bookServer = new BookServer();
	private static int page = 0;

	@Actions({ @Action(base), @Action(base + "/{type}") })
	public String bookList() throws SQLException {
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object username = session.getAttribute("username");
		if (type == null && username != null) {
			name = null ;
			value = null;
			map.put("tjsj", bookServer.allBookData(name,value,0));
			map.put("username", username.toString());
			return "LIST";
		} else if (type == null && username == null) {
			return "OUTLOGIN";
		}
		if ("up".equals(type)) {
			int number = (page - 5) >= 0 ? (page - 5) : page;
			map.put("tjsj", bookServer.allBookData(name,value,number));
			map.put("username", username.toString());
		} else if ("down".equals(type)) {
			int number = (int) bookServer.bookDataCount(name,value);
			number = (page + 5) < number ? (page + 5) : number;
			map.put("tjsj", bookServer.allBookData(name,value,number));
			map.put("username", username.toString());
		}
		return "LIST";
	}

	@Action("/listsearch" + "/{name}/{value}")
	public String searchBook() throws SQLException {
		page = 0 ;
		if (name == null || value == null) {
			return "ERROR";
		}
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object username = session.getAttribute("username");
		map.put("tjsj", bookServer.allBookData(name,value,0));
		map.put("username", username.toString());
		map.put("bookname", value);
		return "LIST";
	}

	public void setType(String type) {
		this.type = type;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void setName(String name) {
		this.name = name;
	}

}
